const { isDev } = require("../config");
const {
  prepayOrder,
  getOrders,
  afterPay,
  getOrderInfo,
  onOrderChange,
} = require("../service/ice/order");
const {
  onOrderHook,
  onOrderUse,
  getFeePrepay,
} = require("../service/ice/order-log");
const { queryPay, onPartnerNotify } = require("../service/ice/paid");
const { onRefund } = require("../service/ice/refund");

const app = require("express").Router();

const notifyPath = "/wxpay-notify";
function getNotifyUrl(req) {
  const origin = isDev ? "https://ice.qs3.fun" : req.origin;
  return origin + req.path0 + "/order" + notifyPath;
}

app.all("/auth/prepay", async (req, res) => {
  const notify_url = getNotifyUrl(req);
  const data = await prepayOrder(req._body, req.user, req.realIp, notify_url);
  res.send(data);
});

app.all("/auth/refund", async (req, res) => {
  const notify_url = getNotifyUrl(req);
  const data = await onRefund(req._body, req.user.id, notify_url);
  res.send(data);
});

app.all(notifyPath, async (req, res) => {
  await onPartnerNotify(req._body);
  res.send("ok");
});

app.all("/hook", (req, res) => {
  onOrderChange(req._body);
  onOrderHook(req._body);
  res.send("ok");
});

app.get("/auth/query", async (req, res) => {
  const data = await afterPay(req.query.order_no, req.user.id);
  res.send(data);
});
app.get("/auth/after-pay", async (req, res) => {
  const data = await afterPay(req.query.order_no);
  res.send(data);
});

app.get("/auth/order-list", async (req, res) => {
  const data = await getOrders(req.query, req.user.id);
  res.send(data);
});
app.get("/auth/order-info", async (req, res) => {
  const data = await getOrderInfo(req._body, req.user);
  res.send(data);
});

app.all("/auth/order-use", async (req, res) => {
  const data = await onOrderUse(req._body, req.user);
  res.send(data);
});

app.get("/auth/fee-prepay", async (req, res) => {
  const notify_url = getNotifyUrl(req);
  const data = await getFeePrepay(req.query, req.realIp, notify_url);
  res.send(data);
});

module.exports = app;
